﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;

namespace CanTIceCream
{
    /// <summary>
    /// 二维码生成
    /// </summary>
    public class EWMMsg
    {
        private static EWMMsg instance;
        private EWMMsg() { }
        public static EWMMsg Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new EWMMsg();
                }
                return instance;
            }
        }
        #region 二维码通讯
        public bool AllBol = true;
        /// <summary>
        ///  IO的通讯返回数据
        /// </summary>
        private List<byte> buffer = new List<byte>();
        public static bool IsMsgError = true;
        string nostrs = "";
        public Thread All_thr;
        public void IOSerial_Thr()
        {
            try
            {
                var ddd = SerialPort.GetPortNames().ToList();
                if (!SerialPort.GetPortNames().ToList().Any(a => a.ToLower().Contains(IPorPortInfo.Instance.EWMPortName)))
                {
                    Thread.Sleep(1000);
                    IOSerial_Thr();
                }
                EWMSerialPort.Instance.IceMachineConnect(IPorPortInfo.Instance.EWMPortName, 115200, "", 8, 1);//其他串口通讯
                EWMSerialPort.Instance.serialPort.DataReceived += SerialPort_DataReceived;
            }
            catch (Exception)
            {
                EWMSerialPort.Instance.serialPort.DataReceived -= SerialPort_DataReceived;
                Thread.Sleep(100);
                IOSerial_Thr();
            }
        }
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                byte[] result = new byte[EWMSerialPort.Instance.serialPort.BytesToRead];
                EWMSerialPort.Instance.serialPort.Read(result, 0, EWMSerialPort.Instance.serialPort.BytesToRead);
                buffer.AddRange(result);
                string str = "";
                if (buffer.Count > 0x03)
                    str += $"{Encoding.ASCII.GetString(result)}";
                MsgShow(str);
                Thread.Sleep(1);
            }
            catch (Exception)
            {
                return;
            }
        }
        public string ewm = "";
        public void MsgShow(string str)
        {
            try
            {
                if (str.Length > 0)
                {
                    Console.WriteLine(str);
                    if (str.Length > 0)
                    {
                        ewm += str;
                        Console.WriteLine(ewm);
                        var msgs = ewm.Split('*');
                        if (msgs.Count() >= 4)
                        {
                            if (nostrs.Length < 18)
                            {
                                str = nostrs + msgs[3];
                                nostrs = "";
                            }
                            else
                                str = msgs[0];
                            var msg = str.Split('#');
                            if (msg.Count() > 1)
                            {
                                if (msg[1].Substring(0, 1) == "3")
                                {
                                    if (iceMetters.Instance.IceMatter1 == 1 && iceMetters.Instance.IceMatter9 == 1)
                                    {
                                        EWM eWM = new EWM();
                                        eWM.orderNum = msg[0];
                                        eWM.deviceId = msg[1].Substring(0, 1);
                                        string list = JsonConvert.SerializeObject(eWM);
                                        var data = HttpMsg.Instance.orderQueueMsg(list);
                                        var listdata = JsonConvert.DeserializeObject<HTTPMsg>(data);
                                        SpeechVoice.Instance.VoicePlayback(listdata.msg);
                                        ewm = "";
                                        Console.WriteLine(listdata.msg);
                                        var ss = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"\ewm\";
                                        File.WriteAllText(ss + DateTime.Now.ToString("yyyyddMMHHmmss") + ".txt", JsonConvert.SerializeObject(str + "  " + eWM.orderNum + " " + eWM.deviceId + " " + listdata.msg));

                                    }
                                    else
                                    {
                                        SpeechVoice.Instance.VoicePlayback("物料短缺，暂时无法制作");
                                    }
                                }
                                else
                                {
                                    
                                    // SpeechVoice.Instance.VoicePlayback("请到 " + msg[1].Substring(0, 1) + " 号机器扫码制作您的咖啡 " + "Please go to Machine No. " + msg[1].Substring(0, 1) + "to scan the QR code to make your coffee");
                                    ewm = "";
                                }
                            }
                            else
                            {
                                if (str.Length > 25)
                                {
                                    ewm = "";
                                }
                                //ewm += str;
                                //EWM eWM = new EWM();
                                //eWM.orderNum = msg[0];
                                //eWM.deviceId = "1";
                                //eWM.type = 1;
                                //string list = JsonConvert.SerializeObject(eWM);
                                //var data = HttpMsg.Instance.orderQueueMsg(list);
                                //var listdata = JsonConvert.DeserializeObject<HTTPMsg>(data);
                                //SpeechVoice.Instance.VoicePlayback(listdata.msg);
                            }
                        }
                        else if (msgs.Count() == 1)
                        {
                            // ewm +=str;
                        }
                    }
                    //var msgs = str.Split('*');
                    //if (msgs.Count() >= 4)
                    //{
                    //    if (nostrs.Length < 18)
                    //    {
                    //        str = nostrs + msgs[3];
                    //        nostrs = "";
                    //    }
                    //    else
                    //        str = msgs[0];
                    //    var msg = str.Split('#');
                    //    if (msg.Count() > 1)
                    //    {
                    //        if (msg[1].Length >= 1)
                    //        {
                    //            if (msg[1].Substring(0, 1) == "2")
                    //            {

                    //                EWM eWM = new EWM();
                    //                eWM.orderNum = msg[0];
                    //                eWM.deviceId = msg[1].Substring(0, 1);
                    //                string list = JsonConvert.SerializeObject(eWM);
                    //                var data = HttpMsg.Instance.orderQueueMsg(list);
                    //                Console.WriteLine(DateTime.Now.ToString("ss:ff"));
                    //                var listdata = JsonConvert.DeserializeObject<HTTPMsg>(data);
                    //                Console.WriteLine(DateTime.Now.ToString("ss:ff"));
                    //                SpeechVoice.Instance.VoicePlayback(listdata.msg);
                    //                var ss = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"\ewm\";
                    //                File.WriteAllText(ss + DateTime.Now.ToString("yyyyddMMHHmmss") + ".txt", JsonConvert.SerializeObject(str + "  " + eWM.orderNum + " " + eWM.deviceId + " " + listdata.msg));
                    //                nostrs = "";
                    //            }
                    //        }
                    //    }
                    //    else
                    //    {
                    //        //EWM eWM = new EWM();
                    //        //eWM.orderNum = msg[0];
                    //        //eWM.deviceId = "2";
                    //        //eWM.type = 0;
                    //        //string list = JsonConvert.SerializeObject(eWM);
                    //        //var data = HttpMsg.Instance.orderQueueMsg(list);
                    //        //Console.WriteLine(DateTime.Now.ToString("ss:ff"));
                    //        //var listdata = JsonConvert.DeserializeObject<HTTPMsg>(data);
                    //        //Console.WriteLine(DateTime.Now.ToString("ss:ff"));
                    //        //SpeechVoice.Instance.VoicePlayback(listdata.msg);
                    //        var ss = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"\ewm\";
                    //        File.WriteAllText(ss + DateTime.Now.ToString("yyyyddMMHHmmss") + ".txt", JsonConvert.SerializeObject(str + "  " + eWM.orderNum + " " + eWM.deviceId + " " + listdata.msg));
                    //      //  nostrs = "";
                    //    }
                    //}
                    //else if (msgs.Count() == 1)
                    //{
                    //    nostrs = msgs[0];
                    //}
                }
            }
            catch (Exception)
            {
                return;
            }
        }
        public class EWM
        {
            public string orderNum { get; set; }
            public string deviceId { get; set; } = "3";
            public int type { get; set; } = 0;//0摩通 1 国贸
        }
        #endregion
    }
}
